//
//  MyActionViewController.swift
//  Woolgathering
//
//  Created by 范东 on 2022/3/7.
//

import UIKit
import HandyJSON

class MyActionsViewController: BaseViewController {
    
    var dataArray = [ActionModel]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = NSLocalizedString("My Actions", comment: "")
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadLocalData()
    }
    
    func loadLocalData(){
        let array = UserDefaults.standard.array(forKey: .myActions)
        if array != nil {
            dataArray.removeAll()
            let newArray = array as! [[String: Any]]
            for item in newArray {
                dataArray.append(ActionModel.deserialize(from: item) ?? ActionModel())
            }
        }
        collectionView.reloadData()
    }
    
    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .systemBackground
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(ActionItemCell.classForCoder(), forCellWithReuseIdentifier: NSStringFromClass(ActionItemCell.classForCoder()))
        return collectionView
    }()

}

extension MyActionsViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ActionItemCell.classForCoder()), for: indexPath) as! ActionItemCell
        if indexPath.item < dataArray.count {
            cell.model = dataArray[indexPath.item]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: floor((UIScreen.main.bounds.size.width - 45) / 2), height: 110)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: String(indexPath.row) as NSCopying) {() -> UIViewController? in
            return nil
        } actionProvider: { (element) -> UIMenu? in
            let addAction = UIAction(title: NSLocalizedString("remove", comment: ""), image: UIImage(systemName: "minus.circle")) { action in
                let model = self.dataArray[indexPath.item]
                var array = UserDefaults.standard.array(forKey: .myActions) as! [Any]
                var tempArray = [[String: Any]]()
                self.dataArray.removeAll()
                for dict in array {
                    let dictModel = ActionModel.deserialize(from: dict as! [String: Any]) ?? ActionModel()
                    if dictModel.id != model.id {
                        tempArray.append(dictModel.toJSON()!)
                        self.dataArray.append(dictModel)
                    }
                }
                UserDefaults.standard.setValue(tempArray, forKey: .myActions)
                UserDefaults.standard.synchronize()
                self.collectionView.reloadData()
            }
            return UIMenu(title:"", children: [addAction])
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let item = dataArray[destinationIndexPath.item]
        dataArray[destinationIndexPath.item] = dataArray[sourceIndexPath.item]
        dataArray[sourceIndexPath.item] = item
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = dataArray[indexPath.item]
        UIApplication.shared.open(URL(string: model.urlScheme+"://")!, options: [:]) { canOpen in
            if !canOpen {
                UIApplication.shared.open(URL(string: model.appUrl)!, options: [:], completionHandler: nil)
            }else{
                let center = UNUserNotificationCenter.current()
                let content = UNMutableNotificationContent()
                content.title = "动作名称："+model.name
                content.subtitle = "所使用的App名称："+model.appName
                content.body = model.desc
                content.sound = .default
                content.badge = NSNumber(value: 1)
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
                let timestamp = Date().timeIntervalSince1970
                let identifier = String(timestamp)
                let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
                center.add(request) { error in
                    if error != nil{
                        DispatchQueue.main.async {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            }
        }
    }
}


